<?php

namespace app\controller\wmapi\purchase;

use App\Library\Y;
use app\model\WaAdmins;
use app\model\WaOrdersQuotationRelevance;
use app\model\WaProducts;
use app\model\WpProductsCans;
use app\controller\wmapi\IndexController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\controller\Crud;
use plugin\admin\app\model\User;
use support\Request;
use support\Response;
use Tinywan\Validate\Validate;
use Workerman\Worker;


class WaProductsController extends Validate
{
    /**
     * 产品列表
     * @param Request $request
     * @return Response
     */
    public function productList(Request $request)
    {
        $param = $request->all();
        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $fields = ['*'];
        $condition = [];
        $conditions = [];
        $between = [];
        if ($param['product_no']) {
            $condition [] = ['product_no', '=', $param['product_no']]; // id
        }

        if ($param['type']) {
            $condition [] = ['type', '=', intval($param['type'])]; // 1 预售待采购 2 库存待销售
        }


        if ($param['series_name']) {
            $condition [] = ['series_name', 'like', '%' . $param['series_name'] . '%']; // 车系名称
        }

        if ($param['model']) {
            $condition [] = ['model', 'like', '%' . $param['model'] . '%']; // 车型名称
        }

        if ($param['brands_name']) {
            $condition [] = ['brands_name', 'like', '%' . $param['brands_name'] . '%']; // 品牌名称
        }

//        if ($param['car_type']) {
//            $condition [] = ['car_type', '=', $param['car_type']]; // 1轿车 2 SUV 3 MPV 4 跑车 5新能源
//        }

//        if ($param['status'] || $param['status'] == 0) {
//            // 0 所有 1 正常 2 过期 4删除
//            if ($param['status'] == 2) {
//                $condition [] = ['expiration_date_end', '<', dateTime()]; // 过期
//            } elseif ($param['status'] == 1) {
//                $condition [] = ['expiration_date_end', '>', dateTime()]; // 正常
//            }
//        }


        $conditions [] = ['status', '!=', 4];
//        if ($param['start_time'] && $param['end_time']) {
//            $between [] = [$param['start_time'], $param['end_time']];
//        }

        $res = WaProducts::list($page, $pageNum, $fields, $condition, $between, $conditions);
        return IndexController::successed($res, '产品列表');

    }

    /**
     * 产品列表 - 不分页
     * @param Request $request
     * @return Response
     */
    public function productListAll(Request $request)
    {
        $param = $request->all();
        $fields = ['*'];
        $condition = [];

        if ($param['model']) {
            $condition [] = ['model', 'like', '%' . $param['model'] . '%']; // 车型名称
        }


        if ($param['product_no']) {
            $condition [] = ['product_no', 'like', '%' . $param['product_no'] . '%']; // 产品编号
        }

        if ($param['type']) {
            $condition [] = ['type', '=', $param['type']]; // 1 预售待采购 2 库存待销售
        }

        $condition [] = ['status', '!=', 4];
//        $condition [] = ['expiration_date_end', '>', dateTime()]; // 正常
        $res = WaProducts::all($fields, $condition);
        return IndexController::successed($res, '产品不分页列表');

    }

    /**
     * 产品创建
     * @param Request $request
     */
    public function productCreate(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if ($param['fuel_form']){
            if ($param['fuel_form'] == '柴油'){
                $vehicle_status = 2;
            }elseif ($param['fuel_form'] == '汽油'){
                $vehicle_status = 2;
            }elseif ($param['fuel_form'] == '油电混合'){
                $vehicle_status = 2;
            }elseif ($param['fuel_form'] == '柴油'){
                $vehicle_status = 2;
            }elseif ($param['fuel_form'] == '48V轻混系统'){
                $vehicle_status = 2;
            }elseif ($param['fuel_form'] == '插电式混合动力'){
                $vehicle_status = 1;
            }elseif ($param['fuel_form'] == '压缩天然气(CNG)'){
                $vehicle_status = 2;
            }elseif ($param['fuel_form'] == '增程式'){
                $vehicle_status = 1;
            }elseif ($param['fuel_form'] == '汽油电驱'){
                $vehicle_status = 2;
            }elseif ($param['fuel_form'] == '氢燃料电池'){
                $vehicle_status = 2;
            }elseif ($param['fuel_form'] == '醇电混合'){
                $vehicle_status = 2;
            }elseif ($param['fuel_form'] == '未知'){
                $vehicle_status = 2;
            }elseif ($param['fuel_form'] == '纯电动'){
                $vehicle_status = 1;
            }
            else{
                $vehicle_status = 2;
            }

        }

        $data = [
            'type' => $param['type'], // 1 预售待采购 2 库存待销售
            'brands_name' => $param['brands_name'], // 品牌名称
            'series_name' => $param['series_name'], // 车系名称
            'model' => $param['model'], // 车型
            'sub_brand_name' => $param['sub_brand_name'], // 厂商
            'market_time' => $param['market_time'], // 上市日期
            'guide_price' => round($param['guide_price'],2), // 指导价
            'retail_concessions' => intval($param['retail_concessions']), // 零售优惠
            'purchase_quotation' => round($param['purchase_quotation'],2), // 采购报价
            'remark' => $param['remark'], // 备注
            'created_at' => date('Y-m-d H:i:s', time()), // 创建时间
            'status' => 1, //
            'admin_id' => $adminId->id,
            'product_no' => IndexController::productSn(),
            'vehicle_status' => $vehicle_status, // 车辆状况(是否是新车)  1 新车 2 二手车
            'car_year' => $param['car_year'], // 上市年款
            'jb' => $param['jb'], // fas报价
            'length' => $param['length'], // fas报价
            'width' => $param['width'], // 宽
            'height' => $param['height'], // 高
            'curb_weight' => $param['curb_weight'], // 设计重量
            'is_nev' => $param['is_nev'], // 动力类型
            'fuel_form' => $param['fuel_form'], // 能源类型
            'series_type' => $param['series_type'], // 车身类型
            'seat_count' => $param['seat_count'], // 座位数
            'driver_form' => $param['driver_form'], // 驱动方式
//            'official_price' => $param['driver_form'], // 指导价
        ];

        if ($param['option_package']){
            $data['option_package']  = json_encode($param['option_package']);// 选装包
        }
        if (array_key_exists('car_id',$param)){
            $data['car_id']  = $param['car_id'];
        }

        if (array_key_exists('model_english',$param)){
            $data['model_english']  = $param['model_english'];
        }

        $condition = [];
        $condition [] = ['series_name', '=', $param['series_name']];
        $condition [] = ['model', '=', $param['model']];
        $condition [] = ['status', '!=', 4];
        $check = WaProducts::find($condition);
        $check = json_decode($check);
        if (!$check) {
            \support\Db::beginTransaction();
            try {
                $res = WaProducts::created($data);
                \support\Db::commit();
                return IndexController::successed($data['product_no'], '产品创建成功');
            } catch (\Exception $exception) {
                \support\Db::rollBack();
                return IndexController::errored($exception, '产品创建失败');
            }

            return IndexController::successed($products, '');
        } else {

            return IndexController::errored('', '该产品已存在不能重复创建');
        }

    }

    /**
     * 产品编辑
     * @param Request $request
     */
    public function productUpdate(Request $request)
    {
        $param = $request->all();
        $adminId = json_decode(adminId($request));

            // 是否新能源 1 是 新能源  2 是 传统能源
            if ($param['fuel_form']){
                if ($param['fuel_form'] == '柴油'){
                    $vehicle_status = 2;
                }elseif ($param['fuel_form'] == '汽油'){
                    $vehicle_status = 2;
                }elseif ($param['fuel_form'] == '油电混合'){
                    $vehicle_status = 2;
                }elseif ($param['fuel_form'] == '柴油'){
                    $vehicle_status = 2;
                }elseif ($param['fuel_form'] == '48V轻混系统'){
                    $vehicle_status = 2;
                }elseif ($param['fuel_form'] == '插电式混合动力'){
                    $vehicle_status = 1;
                }elseif ($param['fuel_form'] == '压缩天然气(CNG)'){
                    $vehicle_status = 2;
                }elseif ($param['fuel_form'] == '增程式'){
                    $vehicle_status = 1;
                }elseif ($param['fuel_form'] == '汽油电驱'){
                    $vehicle_status = 2;
                }elseif ($param['fuel_form'] == '氢燃料电池'){
                    $vehicle_status = 2;
                }elseif ($param['fuel_form'] == '醇电混合'){
                    $vehicle_status = 2;
                }elseif ($param['fuel_form'] == '未知'){
                    $vehicle_status = 2;
                }elseif ($param['fuel_form'] == '纯电动'){
                    $vehicle_status = 1;
                }
                else{
                    $vehicle_status = 2;
                }

            }
        
        
        
        $data = [
            'type' => $param['type'], // 1 预售待采购 2 库存待销售
            'brands_name' => $param['brands_name'], // 品牌名称
            'series_name' => $param['series_name'], // 车系名称
            'model' => $param['model'], // 车型
            'sub_brand_name' => $param['sub_brand_name'], // 厂商
            'market_time' => $param['market_time'], // 上市日期
            'guide_price' => intval($param['guide_price']), // 指导价
            'retail_concessions' => intval($param['retail_concessions']), // 零售优惠
//            'expiration_date_start' => $param['expiration_date_start'], // 产品有效期开始
//            'expiration_date_end' => $param['expiration_date_end'], // 产品有效期结束
//            'purchase_tax' => $param['purchase_tax'], // 购置税
            'purchase_quotation' => intval($param['purchase_quotation']), // 采购报价
            'option_package' => json_encode($param['option_package']), // 选装包
//            'other_price' => json_encode($param['other_price']), // 其它费用
            'remark' => $param['remark'], // 备注
            'created_at' => date('Y-m-d H:i:s', time()), // 创建时间
            'status' => 1, //
            'admin_id' => $adminId->id,
//            'product_no' => IndexController::productSn(),
            'vehicle_status' => $vehicle_status, // 车辆状况(是否是新车)  1 新车 2 二手车
//            'fas_price' => $param['fas_price'], // fas报价
//            'car_type' => $param['car_type'], // 1轿车 2 SUV 3 MPV 4 跑车 5新能源
            'car_year' => $param['car_year'], // 上市年款
//            'supplier_name' => $param['supplier_name'], // 供应商名字
//            'supplier_type' => $param['supplier_type'], // 供应商类型
//            'supplier_id' => $param['supplier_id'],
            'jb' => $param['jb'], // fas报价
            'length' => $param['length'], // fas报价
            'width' => $param['width'], // 宽
            'height' => $param['height'], // 高
            'curb_weight' => $param['curb_weight'], // 设计重量
            'is_nev' => $param['is_nev'], // 动力类型
            'fuel_form' => $param['fuel_form'], // 能源类型
            'series_type' => $param['series_type'], // 车身类型
            'seat_count' => $param['seat_count'], // 座位数
            'driver_form' => $param['driver_form'], // 驱动方式
//            'official_price' => $param['driver_form'], // 指导价

        ];
        if (array_key_exists('car_id',$param)){
            $data['car_id']  = $param['car_id'];
        }
        if (array_key_exists('model_english',$param)){
            $data['model_english']  = $param['model_english'];
        }

        $where [] = ['series_name', '=', $param['series_name']];
        $where [] = ['model', '=', $param['model']];
        $where [] = ['status', '!=', 4];
//        $where [] = ['product_no', '!=', $param['product_no']];
        $find = WaProducts::find($where);
        $find = json_decode($find);

        if ($find) {
            if ($find->product_no != $param['product_no']){
                return IndexController::errored('', '产品更新失败,产品名称已存在');
            }

        }

        $condition = [];
        $condition [] = ['product_no', '=', $param['product_no']];


        \support\Db::beginTransaction();
        try {
            $res = WaProducts::updated($data, $condition);
            if (!$res) {
                \support\Db::rollBack();
                echo $res;
                return IndexController::errored('', '产品更新失败');
            }
            \support\Db::commit();
            return IndexController::successed($res, '产品更新成功');
        } catch (\Exception $exception) {
            \support\Db::rollBack();
            return IndexController::errored($exception, '产品更新失败');
        }

    }

    /**
     * 产品删除
     * @param Request $request
     * @return Response
     */
    public function productDelete(Request $request): Response
    {
//        process($request);
        $adminId = json_decode(adminId($request));
        $param = $request->all();
        $data = [
            'status' => 4, // 4 删除
            'admin_id' => $adminId->id,
            'updated_at' => date('y-m-d h:m:s', time()),
        ];
        $where = [
            'product_no' => $param['product_no'],
        ];
        $delete = WaProducts::updated($data, $where);
        return IndexController::successed($delete, '产品已删除');
//        return parent::delete($request); // TODO: Change the autogenerated stub
    }


    /**
     * 产品-详情
     * @param Request $request
     * @return \support\Response
     */
    public function productDetail(Request $request)
    {
//        process($request);
        $param = $request->all();
        $condition = [];
        $condition [] = ['product_no', '=', $param['product_no']];
        $rule = WaProducts::find($condition);


        // 获取当前这个产品的所有报价单中 行情报价的数据并算出 最低 和 最高 的报价
        $times = time() - (60*60*24*30);
        $start_time = date('Y-m-d H:i:s', $times);
        $condition_purchase_quotation = [];
        $condition_purchase_quotation [] = ['product_no', '=', $param['product_no']];
        $condition_purchase_quotation [] = ['created_at', '>', $start_time];

        $condition_feild = ['count','purchase_quotation','created_at'];
        $ary = [];
        $count = 0;
        $purchase_quotation = 0;
        $quotationOrderChildrenByPurchaseQuotation = WaOrdersQuotationRelevance::allByPurchaseQuotation($condition_feild,$condition_purchase_quotation);
        $quotationOrderChildrenByPurchaseQuotation = json_decode($quotationOrderChildrenByPurchaseQuotation);

        $rule = json_decode($rule);

        if ($quotationOrderChildrenByPurchaseQuotation){
            foreach ($quotationOrderChildrenByPurchaseQuotation as $k){
                $count = $count + round($k->count,2);
                $purchase_quotation = $purchase_quotation + round($k->purchase_quotation,2);
                array_push($ary,round($k->purchase_quotation,2));
            }
            $rule->min_purchase_quotation = reset($ary);
            $rule->average_purchase_quotation = round($purchase_quotation/$count,2);
            $rule->max_purchase_quotation = end($ary);
        }else{
            $rule->min_purchase_quotation = '暂无';
            $rule->average_purchase_quotation = '暂无';
            $rule->max_purchase_quotation = '暂无';
        }
//20*23= 460 + 话费 8 + 30 + 10 = 510 + 电动车充电 10 =520 +茶叶 150 =670 + 车费 50 = 720 +
        $rule->count_purchase_quotation = $count;
        $rule = json_encode($rule);

        return IndexController::successed($rule, '产品信息');
    }
}